﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;
using System.Xml;
using System.Xml.Linq;
using System.IO;
using System.Diagnostics;

namespace bulkuploader_gui
{
    /// <summary>
    /// Interaction logic for home.xaml
    /// </summary>
    public partial class home : Window
    {

        public home()
        {
            InitializeComponent();
            restorePanel.Visibility = Visibility.Hidden;
            if (!File.Exists("appData.xml"))
            {
                XmlDocument doc = new XmlDocument();
                XmlDeclaration dec = doc.CreateXmlDeclaration("1.0", "UTF-8", null);
                doc.AppendChild(dec);
                XmlElement root = doc.CreateElement("apps");
                doc.AppendChild(root);
                doc.Save("appData.xml");
            }
            if (!File.Exists("config.xml"))
            {
                XmlDocument doc = new XmlDocument();
                XmlDeclaration dec = doc.CreateXmlDeclaration("1.0", "UTF-8", null);
                doc.AppendChild(dec);
                XmlElement root = doc.CreateElement("configuration");
                doc.AppendChild(root);
                XmlElement location = doc.CreateElement("backupLocation");
                location.InnerText = "\\GAEbackups";
                doc.ChildNodes[1].AppendChild(location);
                doc.Save("config.xml");
                if (Directory.Exists("\\GAEbackups") == false)
                    Directory.CreateDirectory("\\GAEbackups");
            }
            refreshApplicationListboxBinding();
        }

        private void addAppBtn_Click(object sender, RoutedEventArgs e)
        {
            addNewApp addWindow = new addNewApp();
            addWindow.ShowDialog();
            refreshApplicationListboxBinding();
        }

        private void addEntityBtn_Click(object sender, RoutedEventArgs e)
        {
            String name = getSelectedApp();
            if (name != null)
            {
                addNewEntity addWindow = new addNewEntity(name);
                addWindow.ShowDialog();
                refreshEntityListboxBinding();
            }
            else
                System.Media.SystemSounds.Beep.Play();
        }

        private void removeAppBtn_Click(object sender, RoutedEventArgs e)
        {

            String name = getSelectedApp();
            if (name != null)
            {
                XmlDocument doc = new XmlDocument();
                doc.Load("appData.xml");
                XmlNode temp = doc.SelectSingleNode("//app[@name='" + name + "']");
                doc.DocumentElement.RemoveChild(temp);
                doc.Save("appData.xml");
                refreshApplicationListboxBinding();
                listBox2.ItemsSource = null;
                Directory.Delete("backups/" + name, true);
            }
            else
                System.Media.SystemSounds.Beep.Play();
        }

        private void removeEntityBtn_Click(object sender, RoutedEventArgs e)
        {
            String entityName = (listBox2.SelectedValue as String);
            String name = getSelectedApp();

            if (entityName != null && name != null)
            {
                XmlDocument doc = new XmlDocument();
                doc.Load("appData.xml");
                XmlNode temp = doc.SelectSingleNode("/apps/app[@name='" + name + "']/entity[@id='" + entityName + "']");
                if (temp != null)
                    temp.ParentNode.RemoveChild(temp);
                doc.Save("appData.xml");
                refreshEntityListboxBinding();
            }
            else
                System.Media.SystemSounds.Beep.Play();
        }

        private void listBox1_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            refreshEntityListboxBinding();
        }

        private void refreshApplicationListboxBinding()
        {
            XmlDocument doc = new XmlDocument();
            doc.Load("appData.xml");
            Binding binding = new Binding();
            binding.Source = doc;
            binding.XPath = "//app[@name]/name";
            listBox1.SetBinding(ListBox.ItemsSourceProperty, binding);
        }

        private void refreshEntityListboxBinding()
        {
            String name = getSelectedApp();
            XmlDocument doc = new XmlDocument();
            doc.Load("appData.xml");
            Binding binding = new Binding();
            binding.Source = doc;
            binding.XPath = "//app[@name='" + name + "']/entity/kind";
            listBox2.SetBinding(ListBox.ItemsSourceProperty, binding);
        }

        private void About_Click(object sender, RoutedEventArgs e)
        {
            aboutWindow window = new aboutWindow();
            window.ShowDialog();
        }

        private void startBtn_Click(object sender, RoutedEventArgs e)
        {
            String entityName = (listBox2.SelectedValue as String);
            String name = getSelectedApp();

            if (entityName != null && name != null)
            {
                //check if (backup) or (restore and (file exist) and (file extension = .gbk))
                if (comboBox1.SelectedIndex == 0 || (comboBox1.SelectedIndex == 1 && File.Exists(restoreFileLocationInput.Text) && System.IO.Path.GetExtension(restoreFileLocationInput.Text) == ".gbk"))
                {
                    buildBackupScript();
                    Process.Start("temp.bat");
                }
                else
                    System.Media.SystemSounds.Beep.Play();
            }
            else
                System.Media.SystemSounds.Beep.Play();
        }

        private void buildBackupScript()
        {

            StreamWriter sw = new StreamWriter("temp.bat");
            String appId = getSelectedApp();
            String kind = (listBox2.SelectedValue as String);
            String action = null;
            String command = null;


            if (comboBox1.SelectedIndex == 0) //dump
            {

                String backupLocation = getBackupLocation() + "\\" + appId + "\\" + DateTime.Now.ToString("MM.dd.yyyy");
                if (Directory.Exists(backupLocation) == false)
                    Directory.CreateDirectory(backupLocation);
                action = " --dump";
                command = "bulkloader.py --url=http://" + appId + ".appspot.com/remote_api --filename=\"" + backupLocation + "\\" + kind + "_" + DateTime.Now.ToString("MM-dd-yyyy_HH-mm-ss") + ".gbk\" --kind=" + kind + action;
            }
            else
            {
                String filename = restoreFileLocationInput.Text;
                action = " --restore";
                command = "bulkloader.py --url=http://" + appId + ".appspot.com/remote_api --filename=\"" + filename + "\" --kind=" + kind + action;
            }
            sw.WriteLine("@ECHO OFF");
            sw.WriteLine("cd \\ ");
            sw.WriteLine(command);
            sw.WriteLine("PAUSE");
            sw.WriteLine("CLS");
            sw.WriteLine("EXIT");
            sw.Close();
        }

        private String getSelectedApp()
        {
            XmlElement name = (listBox1.SelectedItem as XmlElement);
            if (name != null)
                return name.InnerText;
            else
                return null;
        }


        private void setBackupLocation_Click(object sender, RoutedEventArgs e)
        {
            changeBackupLocation window = new changeBackupLocation();
            window.ShowDialog();
        }

        private void comboBox1_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            if (comboBox1.SelectedIndex == 0) //dump
            {
                if (restorePanel != null && restorePanel.IsVisible)
                {
                    restorePanel.Visibility = Visibility.Hidden;
                }
            }
            else
            {
                restorePanel.Visibility = Visibility.Visible;
            }
        }

        private void browseBtn_Click(object sender, RoutedEventArgs e)
        {
            System.Windows.Forms.OpenFileDialog dlg = new System.Windows.Forms.OpenFileDialog();
            String backupLocation = getBackupLocation();
            dlg.InitialDirectory = backupLocation;

            dlg.Filter = "GAE datastore backups (*.gbk)|*.gbk";
            dlg.DefaultExt = "gbk";
            //show dialog box
            System.Windows.Forms.DialogResult result = dlg.ShowDialog();

            // OK button was pressed.
            if (result == System.Windows.Forms.DialogResult.OK)
            {
                restoreFileLocationInput.Text = dlg.FileName;
            }
        }

        private String getBackupLocation()
        {

            XmlDocument doc = new XmlDocument();
            doc.Load("config.xml");
            String backupLocation = doc.SelectSingleNode("//backupLocation").InnerText;

            if (backupLocation == null)
            {
                XmlElement location = doc.CreateElement("backupLocation");
                location.InnerText = "backup";
                doc.ChildNodes[1].AppendChild(location);
                doc.Save("config.xml");
                backupLocation = "backup";
            }
            return backupLocation;

        }

        private void exportAppData_Click(object sender, RoutedEventArgs e)
        {
            System.Windows.Forms.SaveFileDialog dlg = new System.Windows.Forms.SaveFileDialog();

            dlg.InitialDirectory = "";

            dlg.Filter = "Application Data XML (*.xml)|*.xml";
            dlg.DefaultExt = "xml";
            //show dialog box
            System.Windows.Forms.DialogResult result = dlg.ShowDialog();

            // OK button was pressed.
            if (result == System.Windows.Forms.DialogResult.OK)
            {

                XmlDocument doc = new XmlDocument();

                try
                {
                    doc.Load("appData.xml");
                    doc.Save(dlg.FileName);
                }
                catch
                {

                }
            }
        }

        private void importAppData_Click(object sender, RoutedEventArgs e)
        {
            System.Windows.Forms.OpenFileDialog dlg = new System.Windows.Forms.OpenFileDialog();

            dlg.InitialDirectory = "";

            dlg.Filter = "Application Data XML (*.xml)|*.xml";
            dlg.DefaultExt = "xml";
            //show dialog box
            System.Windows.Forms.DialogResult result = dlg.ShowDialog();

            // OK button was pressed.
            if (result == System.Windows.Forms.DialogResult.OK)
            {

                XmlDocument doc = new XmlDocument();

                try
                {
                    doc.Load(dlg.FileName);
                    doc.Save("appData.xml");
                }
                catch
                {

                }
                refreshApplicationListboxBinding();
                refreshEntityListboxBinding();
            }
        }
        private void exit_Click(object sender, RoutedEventArgs e)
        {
            this.Close();
        }

        private void helpMenuItem_Click(object sender, RoutedEventArgs e)
        {
            Process.Start("http://code.google.com/p/gae-datastore-backup-utility/");
        }

    }


}
